package cn.edu.imust.loginregisterdemo.register.view;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.Bmob;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;
import cn.edu.imust.loginregisterdemo.R;
import cn.edu.imust.loginregisterdemo.base.BaseFragment;
import cn.edu.imust.loginregisterdemo.login.model.Code;
import cn.edu.imust.loginregisterdemo.login.model.User;
import cn.edu.imust.loginregisterdemo.home.view.MainActivity;
import cn.edu.imust.loginregisterdemo.utils.Utils;

public class UsernameRegisterFragment extends BaseFragment {


    @BindView(R.id.rg_username) EditText       rgUsername;
    @BindView(R.id.rg_password) EditText       rgPassword;
    @BindView(R.id.rg_termOfService) TextView  rgTermOfService;
    @BindView(R.id.rg_pic_code) EditText       rgPicCod;
    @BindView(R.id.rg_pic)      ImageView      rgPic;
    private                     String         currentName;
    private                     String         currentPassword;
    private                     String         realCode;
    private                     String         currentPicCode;
    private                     ProgressDialog pd;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_username_register, container, false);
        Bmob.initialize(getContext(), "33452dfaa0b4f1b9b1a5ea2c1818d5f4");
        ButterKnife.bind(this, view);
        Bitmap hh = Code.getInstance().createBitp();
        rgPic.setImageBitmap(hh);
        realCode = Code.getInstance().getCode().toLowerCase();
        return view;
    }

    @OnClick({R.id.rg_pic, R.id.rg_termOfService, R.id.rg_login})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rg_pic:                                                                   //图片验证码点击事件
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        rgPic.setImageBitmap(Code.getInstance().createBitp());
                        realCode = Code.getInstance().getCode().toLowerCase();
                    }
                }, 900);

                break;
            case R.id.rg_termOfService:
                Utils.showSnackBar(getContext(), view, "服务条款");
                break;
            case R.id.rg_login:
                currentName = rgUsername.getText().toString().trim();                           //去除空格,获取用户名
                currentPassword = rgPassword.getText().toString().trim();                       //去除空格，获取密码
                //去除空格，获取图片验证码
                currentPicCode = rgPicCod.getText().toString().trim();
                if (TextUtils.isEmpty(currentName) || TextUtils.isEmpty(currentPassword)) {     //判断用户名和密码是否
                    Utils.showSnackBar(getContext(), view, "用户名或密码不能为空");
                } else if (realCode.equals(currentPicCode)) {
                    //等待动画
                    pd = new ProgressDialog(getContext());
                    pd.setMessage("正在注册...");
                    pd.show();
                    if (BmobUser.isLogin()) {
                        User user = BmobUser.getCurrentUser(User.class);
                        Utils.showSnackBar(getContext(), view, "已经登录：" + user.getUsername());
                    } else {

                        signUp(view, currentName, currentPassword);
                    }
                } else {
                    Utils.showSnackBar(getContext(), view, "验证码错误");
                }
                break;
        }
    }

    /**
     * 账号密码注册
     */
    private void signUp(final View view, String username, String password) {
        final User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        user.signUp(new SaveListener<User>() {
            @Override
            public void done(User user, BmobException e) {
                if (e == null) {
                    Toast.makeText(getContext(), "注册成功：" + user.getObjectId() + "-" + user.getUsername(), Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getContext(), MainActivity.class));
                } else {
                    Toast.makeText(getContext(), "服务器忙, 请稍后...", Toast.LENGTH_SHORT).show();
                    Log.d("UsernameRegister", "注册失败：" + e.getMessage());
                }
            }
        });
    }

}
